import json
from flask import Flask, request
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_restful import Api
from flask_restful import Resource
import datetime
import config

app = Flask(__name__)
app.config.from_object(config)
db = SQLAlchemy(app)
api = Api(app)


'''数据库模型'''
class CookingRecord(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    idindex = db.Column(db.String(128))
    name = db.Column(db.String(128))
    date_time = db.Column(db.DateTime, default=datetime.datetime.now)
    def return_json(self):
        return {
            'name': self.name,
            'id':self.idindex,
            'sheet':[]
        }

class Item(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    iditem = db.Column(db.Integer)
    crid = db.Column(db.Integer)
    heatcontrol = db.Column(db.Integer)
    time = db.Column(db.Integer)
    def return_json(self):
        return {
            'heatControl': self.heatcontrol,
            'time':self.time
        }

'''
接收分享火候接口
'''
class CookingRecord_add(Resource):
    def post(self):
        data = json.loads(request.get_data())
        duf = CookingRecord(idindex =  data['id'],name = data['name'])
        db.session.add(duf)
        db.session.commit()
        b = CookingRecord.query.filter(CookingRecord.idindex == data['id']).first()
        for dataduf in data['sheet']:
            dufcr = Item(iditem=0, crid=b.id, heatcontrol=dataduf['heatControl'],time=dataduf['time'])
            db.session.add(dufcr)
            db.session.commit()
        return {"st":"ok"}

'''
发送分享火候接口
'''
class CookingRecord_get(Resource):
    def post(self):
        data = json.loads(request.get_data())
        b = CookingRecord.query.filter(CookingRecord.idindex == data['id']).first()
        buf = b.return_json()
        itembuf = Item.query.filter(Item.crid == b.id)
        for duff in itembuf:
            buf['sheet'].append(duff.return_json())
        return buf

api.add_resource(CookingRecord_add, '/CookingRecord_add')
api.add_resource(CookingRecord_get, '/CookingRecord_get')
migrate = Migrate(app, db)
